package com.quickask.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created by NaSa on 2015/9/3.
 */
public class MyFilter implements Filter {

    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("========" + filterConfig.getInitParameter("encoding") + "========");
        encoding = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding(encoding);

        HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;

        //取的url相对地址，例如：/QuickAsk/index.jsp
        String url = httpRequest.getRequestURI();
        System.out.println("url: "+url);
        System.out.println("servletPath: "+httpRequest.getServletPath());
        System.out.println("contextPath: "+httpRequest.getContextPath());

        //获取所有get参数
        Enumeration paramNames = httpRequest.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();

            String[] paramValues = servletRequest.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    System.out.println("参数：" + paramName + "=" + paramValue);
                }
            }
        }

        System.out.println("pathInfo: "+httpRequest.getPathInfo());
        System.out.println("protocol: "+httpRequest.getProtocol());
        System.out.println("Remote scheme : " + servletRequest.getScheme());
        System.out.println("Remote host: " + servletRequest.getRemoteHost());
        System.out.println("Remote port: "+servletRequest.getRemotePort());
        System.out.println("Remote address: "+servletRequest.getRemoteAddr());

        System.out.println("Remote servername: "+servletRequest.getServerName());
        System.out.println("Remote port: "+servletRequest.getServerPort());
        System.out.println("Local address: "+servletRequest.getLocalAddr());
        System.out.println("Local port: "+servletRequest.getLocalPort());
        System.out.println("Local name : "+servletRequest.getLocalName());
        Enumeration enumeration = servletRequest.getAttributeNames();
        while(enumeration.hasMoreElements()) {
            System.out.println("elements: "+enumeration.nextElement());
        }
        servletResponse.setCharacterEncoding(encoding);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
